using Mvc.Mailer;
using ConferenceRegister.Domain;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Web;
using System;
using System.Collections.Generic;

namespace ConferenceRegister.Mailers
{ 
    public class UserMailer : MailerBase 	
	{

        RegisterService Service = new RegisterService();
        HttpContext Context;
        bool Async;
		public UserMailer(HttpContext context, bool async = true)
		{
            Context = context;
			MasterName="_Layout";
            Async = async;
		}
		
		public void ConfirmRegistration(Register model, List<string> emails=null)
		{
            if (emails != null && emails.Count == 0) return;

			model.Conference = Service.All.Conferences.Find(model.ConferenceID); // load conference bcs it fails to lazy load automatically.
            ViewData.Model = model;
            MvcMailMessage message = Populate(x =>
            {
                x.Subject = "You registered for " + model.Conference.Name + "!";
                x.ViewName = "Confirm";
                emails = emails ?? new List<string>() { model.Email };
                emails.ForEach(email => x.To.Add(email));
            });

			if (Async)
			{
				Task.Factory.StartNew(() =>
				{
					System.Web.HttpContext.Current = Context;
					message.Send();
				});
			}
			else message.Send();
        }
		
 	}
}